<?php


namespace app\admin\controller\admin;


use app\admin\annotation\UseAuth;
use app\admin\controller\BaseController;
use app\admin\validate\AdminUserValidate;
use app\common\http\exception\AppException;
use app\common\library\FormDataValidate;
use ke\auth\model\KeUser;
use ke\Model;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Response;
use think\response\Json;

/**
 * Class UsersController
 * @package app\admin\controller\admin
 * @UseAuth(policy="Acl")
 */
class UsersController extends BaseController
{

    /**
     * 管理员列表
     * @return mixed
     * @throws DbException
     * @route('admin/super/users', 'get')
     */
    public function index()
    {
        $result = KeUser::field('password', true)
            ->order('create_time', 'desc')
            ->paginate();

        return $result->render();
    }


    /**
     * 用户详情
     * @param $id
     * @return Response|Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @route('admin/super/user/:id', 'get')
     */
    public function read($id)
    {
        $user = KeUser::where('id', $id)->findOrFail();
        $user->hidden(['password']);

        $user->is_super = $this->auth->isCreateUser($user->id);

        $user->roles = $user->roleAccess()->column('role_id');

        return $this->success($user);
    }


    /**
     * 表单提交
     * @param string $action
     * @return Response|Json
     * @throws AppException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @route('admin/super/user/:action', 'post')
     */
    public function post($action)
    {
        $form = new FormDataValidate(
            AdminUserValidate::class,
            $action
        );

        if (KeUser::where('id', '<>', $form->id)
            ->where('username', $form->username)
            ->value('id')) {
            throw new AppException('账号已存在');
        }
        if ($action === 'edit') {
            $user = KeUser::where('id', $form->id)->findOrFail();
        } else {
            $user = new KeUser();
        }
        Db::transaction(function () use($form, $user) {
            $user->save($form->toArray());
            $this->recordActionLog(sprintf('修改管理%s信息', $user->nickname));

            if (empty($form->roles)) {
                // 清空角色
                $user->roleAccess()->delete();
            } else {
                // 删除不存在数组的roleId
                $user->roleAccess()
                    ->whereNotIn('role_id', $form->roles)
                    ->delete();

                foreach ($form->roles as $role) {
                    $user->roleAccess()->save(['role_id'=>$role]);
                }
            }
        });

        $user->hidden(['password']);

        return $this->success($user);
    }


    /**
     * 角色
     * @param $id
     * @return Response|Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @route('admin/super/user/:id/roles', 'get')
     */
    public function getRole($id)
    {
        $u = KeUser::where('id', $id)->findOrFail();

        return $this->success([
            'list'=>$u->roleAccess()->column('role_id')
        ]);
    }


    /**
     * 角色管理
     * @return Response|Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @route('admin/super/user/role', 'post')
     */
    public function role()
    {
        $form = new FormDataValidate([
            'id'=>'require|number',
            'roles|赋予角色'=>'array'
        ]);

        /**
         * @var KeUser
         */
        $user = KeUser::where('id', $form->id)->findOrFail();

        Db::transaction(function () use($user, $form) {

            if (count($form->roles)) {
                // 删除不存在数组的roleId
                $user->roleAccess()
                    ->whereNotIn('role_id', $form->roles)
                    ->delete();

                foreach ($form->roles as $id) {
                    $user->roleAccess()->save(['role_id'=>$id]);
                }
            } else {
                $user->roleAccess->delete();
            }
        });

        return $this->success();
    }


    /**
     * 删除管理员
     * @param $key
     * @return Response|Json
     * @route('admin/super/user/:key', 'delete')
     */
    public function delete($key)
    {
        $id = explode(',', $key);

        Db::transaction(function () use($id) {
            /**
             * @var KeUser[] $users
             */
            $users = KeUser::with(['roleAccess'])->where('id', 'in', $id)->select();

            foreach ($users as $item) {
                $this->recordActionLog(sprintf('删除角色：%s', $item->name));

                $item->together(['roleAccess'])->delete();
            }

        });
        return $this->success();
    }

}